<?php

namespace App\Console\Commands\Mybank\Tools;

use App\Kuafu\Mybank\Model\MybankEntryModel;
use App\Kuafu\Mybank\Service\MybankOrderWithholdV2Service;
use App\Kuafu\User\Model\User;
use App\Library\FeiShu\SendFs;
use App\Library\KfHttp\TigerCurl;
use Illuminate\Console\Command;
use Kuafu\GeneralFs\BuildFs;

class DelMyBankAccountCommand extends Command
{
    protected $signature   = 'mybank:del-mybank-account {mobile} {forceTiger?}';
    protected $description = '删除网商银行钱包账户';

    private int $userId;

    public function handle()
    {
        $mobile     = $this->argument('mobile');
        $forceTiger = (bool)$this->argument('forceTiger', false); // 强制删除cruise_order

        $user = User::query()->where('mobile', $mobile)->first();
        if (!$user) {
            dd('不存在的手机号');
        }
        $this->userId = $user->id;

        // entry
        $delEntry = $this->delEntry();
        if (!$forceTiger && $delEntry) {
            dd($delEntry);
        }

        // tiger.cruise_order
        $do = TigerCurl::getIns()->do('internal/cruise/delMyBankInput', ['userId' => $this->userId], 'POST');
        if (!$do['code']) {
            dd("cruise_order删除失败： " . $do['msg']);
        } else {
            dump('cruise_order删除成功');
        }

        if ($delEntry != '') {
            dd($delEntry);
        }

        BuildFs::newRobot(SendFs::ROBOT_MY_BANK_DEL)
               ->setTitleContent('网商账号删除成功', "mobile: {$mobile} userId: {$this->userId}")
               ->send();

        $this->info('success');
    }

    private function delEntry()
    {
        $entry = MybankEntryModel::query()->with('shopBindRel')->where('userId', $this->userId)->first();
        if (!$entry) {
            return '不存在的MybankEntryModel';
        }

        if ($entry->shopBindRel->count()) {
            return '该账户已绑定店铺，不能删除';
        }

        // 激活状态：判断余额
        if ($entry->status == MybankEntryModel::STATUS_3) {

            // 余额
            $pay = (new MybankOrderWithholdV2Service())->setMerchantIdByUserId($this->userId)->getBalancePay();
            if ($pay > 0) {
                return '该账户存在余额，不能删除';
            }
        }

        // mybank_entry
        $entry->isDeleted = 1;
        $entry->save();

        dump('mybank_entry删除成功');

        return '';
    }
}
